﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.IO;
using System.Reflection;

namespace ExcelTools
{
    public static class BaseOperation
    {
        public static IWorkbook CreateWorkbook<T>() where T : IWorkbook, new()
        {
            //通过反射实例化workbook对象，规避不同excel版本
            IWorkbook workbook = (IWorkbook)Activator.CreateInstance(typeof(T));

            return workbook;
        }

        /// <summary>
        /// 根据文件获取IWorkbook对象
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns></returns>
        public static IWorkbook GetWorkbook(string path)
        {
            if (File.Exists(path))
            {
                using var file = new FileStream(path, FileMode.Open, FileAccess.Read);
                IWorkbook workbook = WorkbookFactory.Create(file);
                return workbook;
            }
            else
            {
                throw new Exception("未找到对应文件");
            }
        }

        /// <summary>
        /// 保存
        /// <typeparam name="T">HSSFWorkbook:是操作Excel2003以前（包括2003）的版本，扩展名是.xls；XSSFWorkbook、SXSSFWorkbook:是操作Excel2007后的版本，扩展名是.xlsx；</typeparam>
        /// </summary>
        /// <param name="wb">工作簿对象</param>
        /// <param name="path">保存路径</param>
        public static void Save(this IWorkbook wb, string exportPath, string fileName)
        {
            using MemoryStream ms = new MemoryStream();
            wb.Write(ms);

            var exportFullPath = Path.Combine(exportPath, fileName)
                + (wb.GetType() == typeof(HSSFWorkbook) ? ".xls" : ".xlsx");

            using FileStream fs = new FileStream(exportFullPath, FileMode.Create, FileAccess.Write);
            byte[] data = ms.ToArray();
            fs.Write(data, 0, data.Length);
            fs.Flush();
        }

    }
}
